<?php
/** @noinspection PhpUndefinedNamespaceInspection */
/** @noinspection PhpUndefinedClassInspection */
declare(strict_types=1);

namespace herosphp\utils;

use Composer\Package\Package;
use Composer\Script\Event;
use herosphp\GF;

class Plugin
{
    public static function publish(Event $event):void
    {
        $args = $event->getArguments();
        if (empty($args)) {
            GF::printError('ex: composer vendor:publish "herosphp/orm"');
            exit(1);
        }
        $package = new Package(array_shift($args), '*', '*');
        $installPath = $event->getComposer()->getInstallationManager()->getInstallPath($package);
        $tempArr = explode('vendor', $installPath);
        // app config
        $appConfigDir = $tempArr[0].'config'.DIRECTORY_SEPARATOR;
        //vendor config
        $vendorConfigDir = $installPath.DIRECTORY_SEPARATOR.'config';
        $vendorConfigFiles = static::getFiles($vendorConfigDir);

        if (empty($vendorConfigFiles)) {
            GF::printError("no found config file in {$args[0]}");
            exit(1);
        }
        foreach ($vendorConfigFiles as $vendorConfigFile) {
            //app config exist,continue
            $fileName = basename($vendorConfigFile);
            if (file_exists($appConfigDir.$fileName)) {
                GF::printError("{$fileName} config file exist, continue;");
                continue;
            }
            if (copy($vendorConfigFile, $appConfigDir.$fileName)) {
                GF::printSuccess("{$fileName} copy success");
            } else {
                GF::printError("{$fileName} copy error");
            }
        }
        exit(0);
    }

    /**
     * @param string $path
     * @return array
     */
    protected static function getFiles(string $path): array
    {
        if (!file_exists($path)) {
            return [];
        }
        $handle = opendir($path);
        $fileItem = [];
        if ($handle) {
            while (($file = readdir($handle)) !== false) {
                $newPath = $path . DIRECTORY_SEPARATOR . $file;
                if (is_dir($newPath) && $file != '.' && $file != '..') {
                    $fileItem = array_merge($fileItem, self::getFiles($newPath));
                } elseif (is_file($newPath)) {
                    $fileItem[] = $newPath;
                }
            }
        }
        @closedir($handle);
        return$fileItem;
    }
}
